<?php
namespace xcom\model;
use PHPMailer\PHPMailer\PHPMailer;
use x\Xbase;

/**
 * 邮件对象
 */
class Mail extends Xbase {
	public $send_username;
	public $username;
	public $password;
	public $port;
	public $host;

	/**
	 * host:
	 *   aliyun  smtp.aliyun.com
	 *   qq      smtp.qq.com
	 *   163     smtp.163.com
	 */
	public function __construct() {
		parent::__construct();
		$this->send_username = c('type.email_send_username');
		$this->username = c('type.email_username');
		$this->password = c('type.email_password');
		$this->port = c('type.email_port');
		$this->host = c('type.email_host');
	}

	/**
	 * 设置账号
	 * @param  [type] $username [description]
	 * @return [type]           [description]
	 */
	public function init($send_username = "", $username = "", $password = "", $port = "", $host = "") {
		if ($send_username != '') {
			$this->send_username = $send_username;
		}

		if ($username != '') {
			$this->username = $username;
		}

		if ($password != '') {
			$this->password = $password;
		}

		if ($port != '') {
			$this->port = $port;
		}

		if ($host != '') {
			$this->host = $host;
		}

	}
	/**
	 *
	 * @param unknown $phone    电话号码
	 * @param unknown $content  发送内容
	 * @param number $title     发送标题
	 * @param string $code      验证码                        例如 : 123456
	 * @return unknown
	 */
	public function create($email, $title, $content, $code = "") {
		$ip = ip();
		//防止短信轰炸
		if ($code) {
			$sql = "select create_time from mail_history where ip=? and email=? order by id desc limit 1";
			$rs = $this->db->query($sql, [$ip, $email], 1);
			$time = time() - 60;
			if ($rs && $rs['create_time'] > $time) {
				$this->setError("距离上次发送时间不到1分钟！", 'email');
				return false;
			}
		}
		$d = [
			'email' => $email,
			'content' => $content,
			'title' => $title,
			'ip' => $ip,
			'code' => $code,
			'create_time' => time(),
		];
		$id = $this->db->insert('mail_history', $d);
		#验证码入库
		if ($d['code']) {
			$this->db->query('delete from mail_token where create_time<?', [time() - 50 * 60]);
			$this->db->query('delete from mail_token where email=?', [$email]);
			$temp = [
				'email' => $email,
				'code' => $code,
				'token' => token(),
				'mail_history_id' => $id,
				'create_time' => time(),
			];
			$this->db->insert('mail_token', $temp);
		}
		return $id;
	}

	/**
	 * 发送一条
	 * @param unknown $id  表id
	 * 成功返回 token值, 失败返回false
	 */
	public function sendOne($id) {
		$rs = $this->db->query('select * from mail_history where status=0 and id=?', [$id], 1);
		if (!$rs) {
			$this->setError("不存在的邮件任务", 'email');
			return false;
		}
		$this->db->update('mail_history', ['id' => $id, 'status' => 1]);
		$result = $this->send($rs['email'], $rs['title'], $rs['content']);
		if (!$result) {
			$this->db->update('mail_history', ['id' => $id, 'status' => 3]);
			$this->setError('发送失败', 'email');
			return false;
		} else {
			$this->db->update('mail_history', ['id' => $id, 'status' => 2, 'update_time' => time()]);
		}
		return true;
	}

	/**
	 * 发送邮件
	 */
	public function send($email, $title = '验证码', $content = '这是验证码内容') {
		//实例化
		$mail = new PHPMailer();
		try {
			//邮件调试模式
			$mail->SMTPDebug = 0;
			//设置邮件使用SMTP
			$mail->isSMTP();
			// 设置邮件程序以使用SMTP
			$mail->Host = $this->host;
			// 设置邮件内容的编码
			$mail->CharSet = 'UTF-8';
			// 启用SMTP验证
			$mail->SMTPAuth = true;
			// SMTP username
			$mail->Username = $this->username;
			// SMTP password
			$mail->Password = $this->password;
			// 启用TLS加密，`ssl`也被接受
			$mail->SMTPSecure = 'ssl';
			// 连接的TCP端口
			$mail->Port = $this->port;
			//设置发件人
			$mail->setFrom($this->username, $this->send_username);
			//  添加收件人1
			$mail->addAddress($email, $email); // Add a recipient
			//            $mail->addAddress('ellen@example.com');               // Name is optional
			//            收件人回复的邮箱
			$mail->addReplyTo($this->username, $this->send_username);
//            抄送
			//            $mail->addCC('cc@example.com');
			//            $mail->addBCC('bcc@example.com');
			//附件
			//            $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
			//            $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
			//Content
			// 将电子邮件格式设置为HTML
			$mail->isHTML(true);
			$mail->Subject = $title;
			$mail->Body = $content;
//            $mail->AltBody = '这是非HTML邮件客户端的纯文本';
			$mail->send();
			//echo 'Message has been sent';
			$mail->isSMTP();
			return true;
		} catch (Exception $e) {
			//echo 'Mailer Error: ' . $mail->ErrorInfo;
			$this->setError('Mailer Error: ' . $mail->ErrorInfo);
			return false;
		}
	}

	/**
	 * 验证短信码
	 * @param unknown $email, 可以是email, 也可以是token
	 * @param unknown $type
	 * @param unknown $code
	 */
	public function checkCode($email, $code) {
		$rs = $this->db->query('select * from mail_token where email=? or token=?', [$email, $email], 1);
		if (!$rs) {
			return $this->setError('请重新获取验证码', 'email');
		}
		$time = time() - c('type.mail_second');
		if ($rs['create_time'] < $time) {
			$this->db->delete('mail_token', $rs['id']);
			return $this->setError('验证码过期!', 'code');
		}
		if ($rs['code'] != $code) {
			if ($rs['error_times'] > 9) {
				$this->db->delete('mail_token', $rs['id']);
			} else {
				$this->db->update('mail_token', ['id' => $rs['id'], 'error_times' => $rs['error_times'] + 1]);
			}
			return $this->setError('验证错误!', 'code');
		} else {
			$this->db->delete('mail_token', $rs['id']);
			return true;
		}
	}
}
